<template>
  <BaseDrawer v-model="isShow" confirmText="保存" :loading="loading" title="设置角色权限" @confirm="save" @cancel="close">
    <el-tree
        ref="treeRef"
        :data="menuData"
        show-checkbox
        default-expand-all
        node-key="menuId"
        highlight-current
        :props="defaultProps"
    />
  </BaseDrawer>
</template>

<script setup lang="ts">

import {ref} from "vue";
import {saveRoleMenu, selectRoleMenuVOByRoleId} from "/@/api/system/RoleApi";
import {MenuModel} from "/@/api/system/model/MenuModel";
import {RoleMenuModel} from "/@/api/system/model/RoleModel";
const treeRef = ref()
const isShow = ref(false)
const loading = ref(false)
const roleId = ref()
const menuData = ref<MenuModel[]>([])
const defaultProps = {
  label: 'title',
  children: 'children'
}
const init = async (roleIdValue: string) => {
  roleId.value = roleIdValue
  isShow.value = true
  loading.value = true
  let res = await selectRoleMenuVOByRoleId(roleIdValue,()=>{
    loading.value = false
  })
  menuData.value = res.menuAuthAll
  treeRef.value.setCheckedKeys(res.menuIds)
}
const save = async() => {
 let menuIds = treeRef.value.getCheckedKeys()
 let halfMenuIds =  treeRef.value.getHalfCheckedKeys();
  menuIds = menuIds.concat(halfMenuIds)
 let roleMenus = [] as RoleMenuModel[]
  if(menuIds && menuIds.length > 0){
    menuIds.forEach((res: string)=>{
      roleMenus.push({
        menuId: res
      })
    })
  }
  loading.value = true
 await saveRoleMenu({roleId: roleId.value,roleMenus},()=>{
   loading.value = false
 });
  close()
}
const close = () => {
  isShow.value = false
}
defineExpose({init})
</script>

<style scoped>

</style>